package org.jeecg.modules.xl.order.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.xl.exceltemplate.vo.DeliveryCodeSheet;
import org.jeecg.modules.xl.order.dto.XlCustomerOrdeDTO;
import org.jeecg.modules.xl.order.dto.XlCustomerShipmentDTO;
import org.jeecg.modules.xl.order.entity.XlCustomerOrde;
import org.jeecg.modules.xl.order.mapper.XlCustomerOrdeMapper;
import org.jeecg.modules.xl.order.utils.DictUtils;
import org.jeecg.modules.xl.order.vo.OrderSheet;
import org.jeecg.modules.xl.order.vo.OrderSheetDetail;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.xl.order.entity.XlCustomerShipmentDetail;
import org.jeecg.modules.xl.order.entity.XlCustomerShipment;
import org.jeecg.modules.xl.order.vo.XlCustomerShipmentPage;
import org.jeecg.modules.xl.order.service.IXlCustomerShipmentService;
import org.jeecg.modules.xl.order.service.IXlCustomerShipmentDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


 /**
 * @Description: 发货表
 * @Author: jeecg-boot
 * @Date:   2024-10-27
 * @Version: V1.0
 */
@Api(tags="订单发货")
@RestController
@RequestMapping("/xl/xlCustomerShipment")
@Slf4j
public class XlCustomerShipmentController {
	@Autowired
	private XlCustomerOrdeMapper ordeMapper;
	@Autowired
	private IXlCustomerShipmentService xlCustomerShipmentService;
	@Autowired
	private IXlCustomerShipmentDetailService xlCustomerShipmentDetailService;

	 @Autowired
	 private DictUtils dictUtils;
	
	/**
	 * 分页列表查询
	 *
	 * @param xlCustomerShipment
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="订单发货-分页列表查询", notes="订单发货-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<XlCustomerShipment>> queryPageList(XlCustomerShipment xlCustomerShipment,
								   @RequestParam(name="pageType",required = false) Integer pageType,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自 定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("deliveryWay", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("deliveryType", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<XlCustomerShipment> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerShipment, req.getParameterMap(),customeRuleMap);
		Page<XlCustomerShipment> page = new Page<XlCustomerShipment>(pageNo, pageSize);

		if (pageType != null && pageType > 0){
			queryWrapper.lambda()
					//过滤已收货的
					.and(pageType == 2, e-> e.eq(XlCustomerShipment::getState, dictUtils.getDictValue("customer_shipment_state","收货中"))
					)
					.and(pageType == 3 , e-> e.eq(XlCustomerShipment::getState, dictUtils.getDictValue("customer_shipment_state","已收货"))
					)
			;
		}
		//当前操作人
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//当前用户的角色
		String roles = user.getRoleCode();

		//是否管理员角色
//		if (!StrUtil.containsAny(roles, CommonConstant.ADMIN_ROLES)) {
		if (StrUtil.containsAny(roles, "slt_customer")) {//是否是采购人员
			queryWrapper.lambda()
					//筛选自己创建的
					.and(e-> e.eq(XlCustomerShipment::getOrderCreateBy, user.getUsername())
					);
		}
		IPage<XlCustomerShipment> pageList = xlCustomerShipmentService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  *  回传快递单号
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "回传快递单号")
	 @ApiOperation(value="回传快递单号", notes="回传快递单号")
	 @RequiresPermissions("lx:xl_customer_orde:backPass")
	 @RequestMapping(value = "/backPass", method = {RequestMethod.POST})
	 public Result<String> backPass(@RequestBody XlCustomerShipmentDTO dto) {
		 if (StringUtils.isBlank(dto.getDeliveryCode())) {
			 return Result.error("快递单号不能为空！");
		 }

		 XlCustomerShipment byId = xlCustomerShipmentService.getById(dto.getId());
		 if (byId == null){
		 	return Result.error("id找不到对应数据！");
		 }
		 if (StringUtils.isNotBlank(byId.getDeliveryCode())){
			 return Result.error("已回传快递单号！！！不能重复操作！");
		 }
		 try {
			 xlCustomerShipmentService.update(Wrappers.lambdaUpdate(XlCustomerShipment.class)
				 .set(XlCustomerShipment::getDeliveryType, dto.getDeliveryType())
				 .set(XlCustomerShipment::getDeliveryCode, dto.getDeliveryCode())
				 .set(XlCustomerShipment::getUpdateTime, new Date())
				 .eq(XlCustomerShipment::getId, dto.getId())
			 );
			 //维护订单的发货单号
			 ordeMapper.upDeliveryCodes(byId.getOrderCode());
		 } catch (Exception e) {
			 return Result.error("修改出错:"+e.getMessage());
		 }
		 return Result.OK("回传成功!");
	 }


	 /**
	  *  批量物流信息回传
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "批量物流信息回传")
	 @ApiOperation(value="批量物流信息回传", notes="批量物流信息回传")
	 @RequiresPermissions("lx:xl_customer_orde:batchBckPass")
	 @RequestMapping(value = "/batchBckPass", method = {RequestMethod.POST})
	 public Result<String> batchBckPass(@RequestBody XlCustomerShipmentDTO dto) {
		 if (StringUtils.isBlank(dto.getId())) {
			 return Result.error("快递单id不能为空！！");
		 }
		 if (StringUtils.isBlank(dto.getDeliveryCode())) {
			 return Result.error("快递单号不能为空！");
		 }

		 List<String> ids = Arrays.asList(dto.getId().split(","));
		 List<XlCustomerShipment> list = xlCustomerShipmentService.list(Wrappers.lambdaQuery(XlCustomerShipment.class)
		 	.select(XlCustomerShipment::getId,XlCustomerShipment::getShipmentCode,XlCustomerShipment::getOrderCode,XlCustomerShipment::getDeliveryCode)
				 .in(XlCustomerShipment::getId, ids)
		 );

		 ///已有发货单的数据
		 String msgCodes = list.stream().filter(f -> StringUtils.isNotBlank(f.getDeliveryCode())).map(m -> m.getShipmentCode()).collect(Collectors.joining(","));
		 if (list.size() != ids.size()){
			 return Result.error("以下id【"+ids.stream().filter(f-> list.stream().filter(f2-> f2.getId().toString().equals(f)).count() <  1 ).collect(Collectors.joining(","))+"】，找不到！");
		 }else if (StringUtils.isNotBlank(msgCodes)){
			 return Result.error("以下发货单【"+msgCodes+"】，已回传快递单号！！！不能重复操作！");
		 }
		 try {
			 xlCustomerShipmentService.update(Wrappers.lambdaUpdate(XlCustomerShipment.class)
					 .set(XlCustomerShipment::getDeliveryType, dto.getDeliveryType())
					 .set(XlCustomerShipment::getDeliveryCode, dto.getDeliveryCode())
					 .set(XlCustomerShipment::getUpdateTime, new Date())
					 .in(XlCustomerShipment::getId, ids)
			 );

			 //维护订单的发货单号
			 for (XlCustomerShipment shipment : list) {
				 ordeMapper.upDeliveryCodes(shipment.getOrderCode());
			 }
		 } catch (Exception e) {
			 return Result.error("修改出错:"+e.getMessage());
		 }
		 return Result.OK("批量回传成功!");
	 }


	 /**
	  *  收货确认
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "收货确认")
	 @ApiOperation(value="收货确认", notes="收货确认")
	 @RequiresPermissions("lx:xl_customer_orde:takeDelivery")
	 @RequestMapping(value = "/takeDelivery", method = {RequestMethod.POST})
	 public Result<String> takeDelivery(@Valid @RequestBody XlCustomerOrdeDTO dto) {
		 xlCustomerShipmentService.takeDelivery(dto);
		 return Result.OK("确认成功!");
	 }

	 /**
	  *  收货凭证提交
	  * @param dto
	  * @return
	  */
	 @AutoLog(value = "收货凭证提交")
	 @ApiOperation(value="收货凭证提交", notes="收货凭证提交")
	 @RequiresPermissions("lx:xl_customer_orde:submitTakeDelivery")
	 @RequestMapping(value = "/submitTakeDelivery", method = {RequestMethod.POST})
	 public Result<String> submitTakeDelivery(@Valid @RequestBody XlCustomerOrdeDTO dto) {
		 if (StringUtils.isBlank(dto.getImage())){
			 return Result.error("凭证图片不能为空！！");
		 }
		 xlCustomerShipmentService.submitTakeDelivery(dto);
		 return Result.OK("提交成功!");
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "发货表-通过id查询")
	@ApiOperation(value="发货表-通过id查询", notes="发货表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<XlCustomerShipment> queryById(@RequestParam(name="id",required=true) String id) {
		XlCustomerShipment xlCustomerShipment = xlCustomerShipmentService.getById(id);
		if(xlCustomerShipment==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(xlCustomerShipment);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="发货商品表主表ID查询", notes="发货商品表-通主表ID查询")
	@GetMapping(value = "/queryXlCustomerShipmentDetailByMainId")
	public Result<List<XlCustomerShipmentDetail>> queryXlCustomerShipmentDetailListByMainId(@RequestParam(name="id",required=true) Integer id) {
		List<XlCustomerShipmentDetail> xlCustomerShipmentDetailList = xlCustomerShipmentDetailService.selectByMainId(id);
		return Result.OK(xlCustomerShipmentDetailList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param xlCustomerShipment
    */
    @RequiresPermissions("xl:xl_customer_shipment:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlCustomerShipment xlCustomerShipment) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<XlCustomerShipment> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerShipment, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
         List<String> selectionList = Arrays.asList(selections.split(","));
         queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<XlCustomerShipment> xlCustomerShipmentList = xlCustomerShipmentService.list(queryWrapper);

      // Step.3 组装pageList
      List<XlCustomerShipmentPage> pageList = new ArrayList<XlCustomerShipmentPage>();
      for (XlCustomerShipment main : xlCustomerShipmentList) {
          XlCustomerShipmentPage vo = new XlCustomerShipmentPage();
          BeanUtils.copyProperties(main, vo);
          List<XlCustomerShipmentDetail> xlCustomerShipmentDetailList = xlCustomerShipmentDetailService.selectByMainId(main.getId());
          vo.setXlCustomerShipmentDetailList(xlCustomerShipmentDetailList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "发货表列表");
      mv.addObject(NormalExcelConstants.CLASS, XlCustomerShipmentPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("发货表数据", "导出人:"+sysUser.getRealname(), "发货表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

	/** 通过excel导入数据 回传物流快读订单
    *
			* @param request
    * @param response
    * @return
	 */
	 //@RequiresPermissions("lx:xl_customer_orde:importExcel")
	 @RequestMapping(value = "/importBatchExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 // 获取上传文件对象
			 MultipartFile file = entity.getValue();
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setSheetNum(1);	//只导入一个sheet数据
			 params.setStartSheetIndex(0);	//从第一个sheet开始导入
			 params.setNeedSave(false);
			 try {
				 List<DeliveryCodeSheet> list = ExcelImportUtil.importExcel(file.getInputStream(), DeliveryCodeSheet.class, params);

				 if(ObjectUtil.isNotEmpty(list)){
					 for (int i = 0; i < list.size(); i++) {
						 DeliveryCodeSheet deliveryCodeSheet = list.get(i);
						 LambdaUpdateWrapper<XlCustomerShipment> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
						 lambdaUpdateWrapper.eq(XlCustomerShipment::getShipmentCode,deliveryCodeSheet.getShipmentCode());
						 XlCustomerShipment xlCustomerShipment = xlCustomerShipmentService.getOne(lambdaUpdateWrapper);
						 if(ObjectUtil.isNull(xlCustomerShipment) || ObjectUtil.isNotEmpty(xlCustomerShipment.getDeliveryCode())){
							 return  Result.error("发货单数据异常或作已回传了发货单，请核实！！！不能重复操作！");

						 }
						 //更新快递单号
						 xlCustomerShipmentService.update(Wrappers.lambdaUpdate(XlCustomerShipment.class)
								 .set(XlCustomerShipment::getDeliveryWay, "快递")
								 .set(XlCustomerShipment::getDeliveryType, deliveryCodeSheet.getDeliveryType())
								 .set(XlCustomerShipment::getDeliveryCode, deliveryCodeSheet.getDeliveryCode())
								 .set(XlCustomerShipment::getUpdateTime, new Date())
								 .eq(XlCustomerShipment::getShipmentCode, deliveryCodeSheet.getShipmentCode())
						 );
					 }
				 }
				 return Result.OK("文件导入成功！数据行数:" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(),e);
				 return Result.error("文件导入失败:"+e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.OK("文件导入失败！");
	 }

 }
